import { useEffect, useState } from 'react';
import { PageHeader, Button, message } from 'antd';
import { useLocation,useParams} from 'react-router-dom'
import {ArrowLeftOutlined} from '@ant-design/icons'
import E from 'wangeditor'
import Mymodal from '../Mymodal'
import {GetArticleByIdApi,EditArticleApi,AddAricleApi} from '../../request/api'

let editor = null
const Editor = () => {
  const {id} =useParams()
  const [content, setContent] = useState("");
  const [modalTitle, setmodalTitle] = useState("");
  const [modalSubTitle, setmodalSubTitle] = useState("");
  const location = useLocation()
  const [showModal,setShowModal]= useState(false)

  useEffect(() => {
    // 实例化
    editor = new E("#myeditor")

    editor.config.onchange = (newHtml) => {
      setContent(newHtml);
    }

    // 创建
    editor.create()
    if(id){
      GetArticleByIdApi({id}).then(res=>{
        console.log(res)
        if(res.errCode === 0){
          message.success(res.message)
          // setContent(res.data.content)
          editor.txt.html(res.data.content)
          setmodalTitle(res.data.title)
          setmodalSubTitle(res.data.subTitle)
        }else{
          message.error(res.message)
        }
      })
    }else{

    }
    return () => {
      // 组件销毁时销毁编辑器
      editor.destroy()
    }
    // eslint-disable-next-line
  }, [])

  const submitAticleEdit = (values)=>{

    if(id){
      EditArticleApi( 
        {
          ...values,
          content,
          id
        }
      ).then(res=>{
        console.log(res)
        if(res.errCode ===0){
          message.success('文章修改成功')
          setShowModal(false)
        }else{
          message.error(res.message)
        }
      })
    }else{
      AddAricleApi(
        {
          ...values,
          content
        }
      ).then(res=>{
        console.log(res)
        if(res.errCode ===0){
          message.success('文章添加成功')
          setShowModal(false)
        }else{
          message.error(res.message)
        }
      })
    }

    
  }

  return (
    <div className="editor">
      <PageHeader
        style={{padding: 0, marginBottom: '20px'}}
        ghost={false}
        title="文章编辑"
        backIcon={location.pathname === '/edit' ? false : <ArrowLeftOutlined/>}
        onBack={()=>{}}
        subTitle={`当前日期：${new Date().getFullYear()}-${new Date().getMonth()+1}-${new Date().getDate()}`}
        extra={[
          <Button key="3" type="primary" onClick={()=>{setShowModal(true)}}>提交文章</Button>,
        ]}
      ></PageHeader>
      <div id="myeditor"></div>
      <Mymodal showModal={showModal} setShowModal = {setShowModal} title={modalTitle} subTitle={modalSubTitle} submitAticleEdit={submitAticleEdit}/>
    </div>
  );
}

export default Editor;
